package my.diplom.web.controllers;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.BindException;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import my.diplom.entity.*;
import my.diplom.dao.service.*;
import my.diplom.util.OrderUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.text.SimpleDateFormat;
import java.beans.PropertyEditorSupport;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 13.09.2009
 * Time: 15:12:50
 * To change this template use File | Settings | File Templates.
 */
public class ResourceController extends SimpleFormController {

    private ResourceService resourceService;
    private OrderService orderService;
    private StatusService statusService;
    private ProjectService projectService;
    private HostService hostService;


    public ResourceController() {
        setCommandClass(Resource.class);
        setCommandName("newResource");
        setSessionForm(false);
        setBindOnNewForm(false);
    }

    public void setHostService(HostService hostService) {
        this.hostService = hostService;
    }

    public void setProjectService(ProjectService projectService) {
        this.projectService = projectService;
    }

    public void setResourceService(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    public void setStatusService(StatusService statusService) {
        this.statusService = statusService;
    }

    @Override
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        if (request.getParameter("resourceId") != null && request.getParameter("action").equals("edit")) {
            Resource resource = resourceService.getById(Long.parseLong(request.getParameter("resourceId")));
            request.setAttribute("editedResource", resource);
            return resource;
        } else {
            Resource resource = new Resource();
            return resource;
        }
    }

    @Override
    protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
        HashMap<String, Object> model = new HashMap<String, Object>();
        List<Resource> resources = resourceService.getAll();
        List<Float> cpuList = OrderUtil.getCpuList(getServletContext());
        List<Float> hddList = OrderUtil.getHddList(getServletContext());
        List<Float> ramList = OrderUtil.getRamList(getServletContext());
        List<Status> statuces = statusService.getResourceStatuces();
        List<Project> projects = projectService.getAll();
        List<Host> hosts = hostService.getAll();
        model.put("hosts", hosts);
        model.put("statuces", statuces);
        model.put("cpuList", cpuList);
        model.put("hddList", hddList);
        model.put("ramList", ramList);
        model.put("resources", resources);
        model.put("projects", projects);
        return model;
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
        Resource resource = (Resource) command;
        resourceService.create(resource);
        return new ModelAndView(new RedirectView("createResource.htm"));
    }

    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

        binder.registerCustomEditor(Date.class, "startDate", new CustomDateEditor(dateFormat, false) {

        });

        binder.registerCustomEditor(Date.class, "finishDate", new CustomDateEditor(dateFormat, false) {

        });

        binder.registerCustomEditor(Set.class, "projects", new CustomCollectionEditor(Set.class) {


            protected Object convertElement(Object element) {
                if (element != null) {
                    Long projectId = Long.parseLong(element.toString());
                    Project project = projectService.getById(projectId);
                    return project;
                }
                return null;
            }

        });

        binder.registerCustomEditor(Status.class, "status", new PropertyEditorSupport() {

            public void setAsText(String text) {
                if (text instanceof String) {
                    if (text != null && text.trim().length() > 0) {
                        Long statusId = Long.parseLong(text);
                        Status status = statusService.getById(statusId);
                        setValue(status);
                    }

                }
            }

            public String getAsText() {
                Object value = getValue();
                if (value != null) {
                    Status status = (Status) value;
                    return status.getStatusName();
                }
                return null;
            }


        });

        binder.registerCustomEditor(Host.class, "host", new PropertyEditorSupport() {

            public void setAsText(String text) {
                if (text instanceof String) {
                    if (text != null && text.trim().length() > 0) {
                        Long hostId = Long.parseLong(text);
                        Host host = hostService.getById(hostId);
                        setValue(host);
                    }

                }
            }
        });


    }


}
